package com.crazyhat.crazyhat.service.impl;

import com.crazyhat.crazyhat.service.IVerificationCodeService;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    private static final long CODE_EXPIRATION_TIME = 5 * 60 * 1000; // 5 minutes in milliseconds
    private static final long RATE_LIMIT_TIME = 60 * 1000; // 1 minute in milliseconds

    private final ConcurrentHashMap<String, CodeEntry> codeStorage = new ConcurrentHashMap<>();

    @Override
    public void saveCode(String email, String code) {
        codeStorage.put(email, new CodeEntry(code, System.currentTimeMillis()));
    }

    @Override
    public String getCode(String email) {
        CodeEntry entry = codeStorage.get(email);
        return entry != null ? entry.getCode() : null;
    }

    @Override
    public boolean isCodeValid(String email, String code) {
        CodeEntry entry = codeStorage.get(email);
        if (entry == null) {
            return false;
        }
        long currentTime = System.currentTimeMillis();
        if (currentTime - entry.getTimestamp() > CODE_EXPIRATION_TIME) {
            codeStorage.remove(email);
            return false;
        }
        return code.equals(entry.getCode());
    }

    @Override
    public boolean canSendCode(String email) {
        CodeEntry entry = codeStorage.get(email);
        if (entry == null) {
            return true;
        }
        long currentTime = System.currentTimeMillis();
        return currentTime - entry.getTimestamp() > RATE_LIMIT_TIME;
    }

    private static class CodeEntry {
        private final String code;
        private final long timestamp;

        public CodeEntry(String code, long timestamp) {
            this.code = code;
            this.timestamp = timestamp;
        }

        public String getCode() {
            return code;
        }

        public long getTimestamp() {
            return timestamp;
        }
    }
}
